const Controller = require("egg").Controller;
const errorLog = require("../utils/errorLog");

class menuController extends Controller {
  async createMenu() {
    try {
      const menuObj = this.ctx.request.body;
      const menu = await this.ctx.service.menu.createMenu(menuObj);
      if (menu) {
        this.ctx.body = {
          code: 200,
          data: menu,
          msg: "创建成功",
        };
      } else {
        this.ctx.body = {
          code: 500,
          msg: "创建失败",
        };
      }
    } catch (err) {
      errorLog("menuController----->createMenu", err);
    }
  }
  async deleteMenu() {
    try {
      const id = this.ctx.request.body.id;
      const menu = await this.ctx.service.menu.deleteMenu(id);
      if (menu) {
        this.ctx.body = {
          code: 200,
          msg: "删除成功",
        };
      } else {
        this.ctx.body = {
          code: 500,
          msg: "删除失败",
        };
      }
    } catch (err) {
      errorLog("menuController----->deleteMenu", err);
    }
  }
  async updateMenu() {
    try {
      const menuObj = this.ctx.request.body;
      const menu = await this.ctx.service.menu.updateMenu(menuObj);
      if (menu) {
        this.ctx.body = {
          code: 200,
          msg: "更新成功",
        };
      } else {
        this.ctx.body = {
          code: 500,
          msg: "更新失败",
        };
      }
    } catch (err) {
      errorLog("menuController----->updateMenu", err);
    }
  }
  async getMenuList() {
    try {
      const menuList = await this.ctx.service.menu.getMenuList();
      if (menuList) {
        this.ctx.body = {
          code: 200,
          data: menuList,
          msg: "获取成功",
        };
      } else {
        this.ctx.body = {
          code: 500,
          msg: "获取失败",
        };
      }
    } catch (err) {
      errorLog("menuController----->getMenuList", err);
    }
  }

  async getMenuTree() {
    try {
      const requestRoleId = this.ctx.state.user.roleId;
      let res;
      if (requestRoleId === 3) {
        res = await this.ctx.service.menu.getMenuList();
      } else {
        res = await this.ctx.service.menu.getMenuTreeByRoleId(requestRoleId);
      }
      if (res) {
        this.ctx.body = {
          code: 200,
          data: res,
          msg: "获取成功",
        };
      } else {
        this.ctx.body = {
          code: 500,
          msg: "获取失败",
        };
      }
    } catch (err) {
      errorLog("menuController----->getMenuTreeNyRoleId", err);
      return false;
    }
  }
}

module.exports = menuController;
